package com.skyon.sdk;

import android.content.Context;
import android.util.Log;

import com.skyon.sdk.bean.ResultBean;

public class MSUCrashHanderUtil implements Thread.UncaughtExceptionHandler {

    private Thread.UncaughtExceptionHandler mDefaultHandler;
    private static MSUCrashHanderUtil INSTANCE = new MSUCrashHanderUtil();
    private Context mContext;

    private MSUCrashHanderUtil() {
    }

    public static MSUCrashHanderUtil getInstance() {
        return INSTANCE;
    }

    public void init(Context context) {
        mContext = context;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        MSUCommon.isError = true;
        if (!handleException(ex) && mDefaultHandler != null) {
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.exit(0);
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

    private boolean handleException(final Throwable throwable) {
        if (throwable == null) {
            return false;
        }
        collectInfo(throwable);
        return true;
    }

    private void collectInfo(final Throwable throwable) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                ResultBean errorBean = MSUCommon.resultBean.setUpErrorInfo(mContext, throwable, new ResultBean());
                MSUHttpUtils.mPost(errorBean.toString());
                Log.d("SkyonSdk:", "collectError......" + errorBean.toString());
            }
        }).start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}